// export const bUrl = "https://duxinggj.com/"
// export const bUrl = "http://127.0.0.1:8360/"
// #ifdef APP-PLUS
var AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
const plugin = uni.requireNativePlugin('GW-ChooseFileModule')
// #endif

// export const bUrl = "http://axedapi.firstresponseman.cn/"
// let apiurl = 'https://www.lingju168.com/regulator/api/regulator/'
let apiurl = 'https://h5.shengu.info/'
// if (process.env.NODE_ENV == 'development') {
//   apiurl = "https://test.shengu.info/"
// }
export const bUrl = apiurl
// 退出
export const outInt = () => {
	uni.showLoading({
		title: "退出"
	})
	try {
		uni.clearStorageSync();
	} catch (e) {
		// error
	}
	uni.reLaunch({
		url: '/pages/user/login'
	});
}
export const callBack = () => {
	// 在C页面内 navigateBack，将返回A页面
	uni.navigateBack();
}
export const transferTimeYMD = (t) => {
	const time = new Date(t);
	const Year = time.getFullYear(),
		Month = time.getMonth() + 1,
		Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();
	return `${Year}-${Month}-${Data}`;
}
export const transferTimeYMDHm = (t) => {
	const time = new Date();
	const Year = time.getFullYear(),
		Month = time.getMonth() + 1,
		Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
		hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
		Minutes =
		time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
		Seconds =
		time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
	return `${Year}-${Month}-${Data} ${hour}:${Minutes}`;
};
export const duibisa = (iuiwa) => {
	try {
		const dsfdsra = iuiwa.split(" ")[0]
		const dsfdsrb = iuiwa.split(" ")[1].split("--")[1]
		const datea = new Date(dsfdsra + ' ' + dsfdsrb + ":00:00:00").getTime()
		const dateb = new Date().getTime()
		return datea < dateb ? true : false
	} catch (e) {
		return false
	}

}
export const duibisaer = (iuiwa) => {
	const datea = new Date(iuiwa + ":00").getTime()
	const dateb = new Date().getTime()
	return datea < dateb ? true : false

}

/**
 * @description 时间戳转为多久之前
 * @param {String|Number} timestamp 时间戳
 * @param {String|Boolean} format 
 * 格式化规则如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 * @returns {string} 转化后的内容
 */
export const timeFrom = (timestamp = null, format = 'yyyy-mm-dd') => {
	let timer = (new Date()).getTime() - new Date(timestamp)
	timer = parseInt(timer / 1000)
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = ''
	switch (true) {
		case timer < 300:
			tips = '刚刚'
			break
		case timer >= 300 && timer < 3600:
			tips = `${parseInt(timer / 60)}分钟前`
			break
		case timer >= 3600 && timer < 86400:
			tips = `${parseInt(timer / 3600)}小时前`
			break
		case timer >= 86400 && timer < 2592000:
			tips = `${parseInt(timer / 86400)}天前`
			break
	}
	return tips
}
// 验证手机号
export const yzphone = (a) => {
	var b = !1;
	return (
		a.match(
			/^13[0-9]{9}|15[0-9]{9}|14[0-9]{9}|19[0-9]{9}|16[0-9]{9}|17[0-9]{9}|18[0-9]{9}$/
		) &&
		11 == a.length &&
		(b = !0),
		b
	);
};


/**
 * @param len 随机数的长度
 * @return 随机数
 **/
export const randomString = (len) => {
	len = len || 32;
	var $chars = "1234567890"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = "";
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}
export const dxrequest = (url, data, method, tps) => {
	if (!data) {
		data = {}
	}
	const userInfo = uni.getStorageSync("userInfo")
	if (userInfo.departmentId) {
		data.departmentId = userInfo.departmentId
	}
	for (let key in data) {
		if (!data[key]) {
			delete data[key]
		}
	}
	if (tps) {
		url = url + '?' + duixiangzhuan(data)
	}
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync("token")
		if(localStorage.token){
			token = localStorage.token
		}
		uni.request({
			url: bUrl + url, //仅为示例，并非真实接口地址。
			data: data,
			method: method || "get",
			header: {
				token: token,
			},
			success: (res) => {
				resolve(res.data);
			},
			fail: (res) => {
				console.log(res)
			}
		});
	})
}

export const dxrequestqz = (url, data, method) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync("token")
		uni.request({
			url: url, //仅为示例，并非真实接口地址。
			data: data,
			method: method || "get",
			success: (res) => {
				resolve(res.data);
			},
			fail: (res) => {
				console.log(res)
			}
		});
	})
}
export const duixiangzhuan = (data) => {
	var _result = [];
	for (var key in data) {
		var value = data[key];
		try {
			if (value.constructor == Array) {
				value.forEach(function(_value) {
					_result.push(key + '=' + value + '');
				});
			} else {
				_result.push(key + '=' + value);
			}
		} catch (e) {}
	}
	return _result.join('&');
}

export const VerifyTheLogin = () => {
	let userInfo = uni.getStorageSync("userInfo")
	if (!userInfo) {
		uni.reLaunch({
			url: '/pages/userCnter/loading'
		});
	}
	return userInfo
}
export const jsonToString = (data) => {
	let string = "";
	try {
		const _result = [];
		for (const key in data) {
			const value = data[key];
			if (value.constructor == Array) {
				value.forEach(function() {
					_result.push(key + "=" + value);
				});
			} else {
				_result.push(key + "=" + value);
			}
			string = _result.join("&");
		}
	} catch (e) {
		console.log(e);
	}
	return string;
}
export const hf = (url, data) => {
	uni.navigateTo({
		url: url
	})
}
export const czhf = (url, data) => {
	console.log(data)
	console.log(url + "?" + duixiangzhuan(data))
	uni.navigateTo({
		url: url + "?" + duixiangzhuan(data)
	})
}
export const hfer = (url) => {
	uni.redirectTo({
		url: url
	})
}
export const hfsan = (url) => {
	uni.switchTab({
		url: url
	})
}


// 申报方式
export const DeclareMeans = [{
		label: "自主申报",
		value: 0,
	},
	{
		label: "官方申报",
		value: 1,
	},
];
export const opfile = (url) => {
	uni.downloadFile({
		url,
		success: function(res) {
			var filePath = res.tempFilePath;
			uni.openDocument({
				filePath: filePath,
				showMenu: true,
				success: function(res) {
					console.log('打开文档成功');
				}
			});
		}
	});
}

export const chooseMessageFile = () => {
	return new Promise((resolve, reject) => {
		uni.chooseMessageFile({
			count: 1, //默认100
			extension: ['.pdf'],
			success: function(res) {
				// 上传文件
				console.log(res.tempFiles[0])

				uni.uploadFile({
					url: bUrl + 'public/Upimg', //上传图片的路径
					filePath: res.tempFiles[0].path, // 这个是选中的文件
					name: 'file',
					formData: {
						'typeName': 'xtgxpdf'
					},
					success: (uploadFileRes) => {

						uni.hideLoading()
						const data = JSON.parse(uploadFileRes.data)
						console.log(data)
						resolve({
							pdf: data.data.imgurl.split("?imageMogr2")[0]
						})
					},
					fail: (data) => {
						console.log(data)
					}
				});


			}
		});
	})
}
export const dxrequestht = (url, data, method) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url, //仅为示例，并非真实接口地址。
			data: data,
			method: method || "get",
			success: (res) => {

				resolve(res.data);
			}
		});
	})
}

export const dxgetLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy: true,
			async success(res) {
				const {
					data
				} = await dxrequestht("https://duxinggj.com/public/reverseGeocoding", {
					location: res.latitude + ',' + res.longitude
				})
				resolve({
					...data,
					latitude: res.latitude,
					longitude: res.longitude
				})
			},
			fail(e) {
				// uni.showToast({
				// 	title:"系统尝试重新获取位置信息，请稍等",
				// 	icon:"none"
				// })
				resolve({
					data: false
				})
			}
		})
	})
}

// 上传图片
export const upImg = () => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, //默认9
			success: function(res) {
				uni.showLoading({
					title: "上传中..."
				})
				const imgName = res.tempFiles[0].name
				uni.uploadFile({
					url: bUrl + 'public/Upimg', //仅为示例，非真实的接口地址
					filePath: res.tempFilePaths[0],
					name: 'file',
					formData: {
						'typeName': 'peixun'
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						const data = JSON.parse(uploadFileRes.data)
						console.log(data)
						resolve({
							name: imgName,
							imgurl: data.data.imgurl
						})
					}
				});
			},
			fail(data) {
				console.log(data)
				uni.hideLoading()
			}
		});
	})
}
// 上传图片
export const upImgnch = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "上传中"
		})
		uni.uploadFile({
			url: 'https://duxinggj.com/public/Upimg', //仅为示例，非真实的接口地址
			filePath,
			name: 'file',
			formData: {
				'typeName': '医保美'
			},
			success: (uploadFileRes) => {
				uni.hideLoading()
				const data = JSON.parse(uploadFileRes.data)
				console.log(data)
				resolve({
					imgurl: data.data.imgurl
				})
			}
		});
	})
}
// 获取系统信息
export const xtInfo = () => {
	return new Promise((resolve, reject) => {
		plus.runtime.getProperty(plus.runtime.appid, function(inf) {
			resolve(inf); // .versionCode
		});
	})
}

// 下载wgt

export const downWgt = (wgtUrl) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "下载文件中..."
		})
		plus.downloader.createDownload(wgtUrl, {
			filename: "_doc/update/"
		}, function(d, status) {
			if (status == 200) {
				resolve(d.filename); // 安装wgt包  
			} else {
				console.log("下载wgt失败！");
				plus.nativeUI.alert("下载wgt失败！");
			}
			uni.hideLoading()
		}).start();
	})
}

// 安装

export const installWgt = (path) => {
	plus.runtime.install(path, {}, function() {
		plus.nativeUI.alert("应用资源更新完成！", function() {
			plus.runtime.restart();
		});
	}, function(e) {
		console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
	});
}

export const dxSToast = (title) => {
	uni.showToast({
		icon: "none",
		title: title
	})
}


// 随机数
export const rand = () => {
	const min = 1000,
		max = 9999
	return Math.floor(Math.random() * (max - min)) + min;
}


// 上传pdf
export const upflie = () => {
	return new Promise((resolve, reject) => {
		plugin.chooseFile({
				// 非必填，选择文件最大数量
				count: 1,
				// 非必填，指定文件扩展名
				extension: ["pdf", "zip"],
				// 非必填，指定目录，可指定任意多个目录
				paths: [{
					deep: false, // deep为true表示扫描文件包含指定目录及以下的全部子目录，false表示只扫描指定目录下一级的文件
					path: 'Download' // 指定根目录下的相对目录，不用写根目录（/storage/emulated/0）
				}, ]
			},
			res => {
				console.log(res)
				uni.showToast({
					icon: "none",
					title: JSON.stringify(res)
				})
				uni.showLoading({
					title: "上传中..."
				})
				const pathHolp = res.files[0].path
				const pdfName = res.files[0].name
				const extension = res.files[0].extension
				uni.uploadFile({
					url: bUrl + 'public/Upimg', //仅为示例，非真实的接口地址
					filePath: pathHolp,
					name: 'file',
					formData: {
						'typeName': 'syfile'
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						const data = JSON.parse(uploadFileRes.data)
						let imgurl = data.data.imgurl
						try {
							imgurl = imgurl.split("?")[0]
						} catch (e) {

						}
						resolve({
							name: pdfName,
							imgurl,
							pathHolp,
							extension
						})
					}
				});

				/*
		        返回示例
		        {
		            "files": [
		                {
		                     // 本地存储路径，uni 上传前面需要添加 file://
		                    "path": "/storage/emulated/0/Download/a.xlsx",
		
		                     // 文件名
		                    "name": "a.xlsx",
		
		                     // 最后修改时间(毫秒)
		                    "lastModified": 1658113714000,
		
		                    // 大小(Byte)
		                    "size": 10049,
		
		                     // 扩展名
		                    "extension": "xlsx",
		
		                    // mimeType
		                    "mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
		                }
		            ]
		        }
		        */
			}
		)



		// AfDocument.openMode({
		// 	size: '1', //选择总数量
		// 	paths: ['/storage/emulated/0/Download', '/storage/emulated/0/A', ], //自定义选择目录
		// 	isDown: true, //是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
		// 	types: [{
		// 		name: '请选择方案文件',
		// 		value: ["pdf","jpge","png","jpg","zip"]
		// 	}]
		// }, (res) => {
		// 	uni.showLoading({
		// 		title: "上传中..."
		// 	})
		// 	const pdfName = res.res[0].name
		// 	const pathHolp = res.res[0].pathHolp
		// 	uni.uploadFile({
		// 		url: bUrl + 'public/Upimg', //仅为示例，非真实的接口地址
		// 		filePath: pathHolp,
		// 		name: 'file',
		// 		formData: {
		// 			'typeName': 'axedpdf'
		// 		},
		// 		success: (uploadFileRes) => {
		// 			uni.hideLoading()
		// 			const data = JSON.parse(uploadFileRes.data)
		// 			resolve({
		// 				name: pdfName,
		// 				imgurl: data.data.imgurl,
		// 				pathHolp
		// 			})
		// 		}
		// 	});
		// })
	})
}

export const jiamiphone = (phone) => {
	return phone.substring(0, 3) + '****' + phone.substring(7, 11)


}

// 支付
export const zhifu = async (jg) => {
	return new Promise(async(resolve, reject) => {
		uni.showLoading({
			title: "加载中..."
		})
		const {
			data
		} = await dxrequest("wechar/zhifu/index", {
			openid: uni.getStorageSync("openid"),
			amount: jg
		})
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.Ppackage,
			signType: data.signType,
			paySign: data.paySign,
			success: function(res) {
				uni.hideLoading()
				resolve(true)
			},
			fail: function(err) {
				uni.hideLoading()
				resolve(false)
			}
		})
	})
}

export const LogBackin = () => {
  // const wlf = window.location.href;
  let wlf= 'https://h5.shengu.info/xqw.html'
  const cdx = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
    window.appId
  }&redirect_uri=${encodeURIComponent(
    wlf
  )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"`;
  window.location.href = cdx;
};